package edu.hawaii.myisern.users;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Class to store username and password.
 * @author John Hauge
 *
 */
public class User { 
  /** Username. */
  public String name;
  /** Password. */
  public String password;
  private static Logger logger = Logger.getLogger("edu.hawaii.myisern.Hauge");
  private String key = "myisern";
  /**
   * Constructor.
   * @param name Username.
   * @param password Password.
   * @throws NoSuchAlgorithmException if error occurs.
   */
  public User(String name, String password) throws NoSuchAlgorithmException {
    try {
      this.name = name;
      this.password = getMD5Hash(password, this.key);
    }
    catch (Exception e) {
      logger.log(Level.SEVERE, e.toString());
    }
  }
  
  /**
   * Overridden hashCode() method.
   * hashCode that combines two strings from 
   * http://mindprod.com/jgloss/hashcode.html.
   * @return a hash code value on the pair of strings.
   */
  public int hashCode() {
    int result = 17;
    result = 37 * result + this.name.hashCode();
    result = 37 * result + this.password.hashCode();
    return result;
}
  /**
   * Overridden equals() method.
   * @param o Object to compare.
   * @return True/False.
   */
  public boolean equals(Object o) {
    try {
      if (o == null) {
        return false;
      }
      else {
        boolean pass = false;
        User u = (User) o;
        if (this.name.equals(u.name) && 
            this.password.equals(u.password)) {
          pass = true;
        }
        return pass;
      }
    }
    catch (Exception e) {
      logger.log(Level.SEVERE, e.toString());
      return false;
    }
  }
  /**
   * Code snippet from http://snippets.dzone.com/posts/show/3923.
   * @param data to encode.
   * @param key cypher.
   * @return string of hex representation of the MD5 hash.
   */
    public static String getMD5Hash(String data, String key) {
      try {
          MessageDigest md5 = MessageDigest.getInstance("MD5");
          md5.update(data.getBytes());
          byte result[] = md5.digest(key.getBytes());
          StringBuffer sb = new StringBuffer();
          for (int i = 0; i < result.length; i++) {
              String s = Integer.toHexString(result[i]);
              int length = s.length();
              if (length >= 2) {
                  sb.append(s.substring(length - 2, length));
              } else {
                  sb.append('0');
                  sb.append(s);
              }
          }
          return sb.toString();
          
      } 
      catch (NoSuchAlgorithmException e) {
        logger.log(Level.SEVERE, e.toString());
        return null;
      }
    }
}
